package com.weasel.im.server.handler;

import com.weasel.im.common.domain.IMSession;
import com.weasel.im.common.domain.Message;
import com.weasel.im.common.manager.IMSessionManager;
import com.weasel.im.common.manager.LeaveMessageCacheManager;
import com.weasel.im.common.manager.UserSessionRelationManager;
import com.weasel.im.server.executor.MessageExecutorChain;
import com.weasel.im.server.initializer.CommonMessageHandlerInitializer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Dylan on 2015/11/27.
 */
public class JettyIMServerHandler extends SimpleChannelInboundHandler<Message> {

    private final static Logger logger = LoggerFactory.getLogger(JettyIMServerHandler.class);
    /*private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);*/
    private MessageExecutorChain executor;
    private IMSessionManager sessionManager;

    public JettyIMServerHandler(IMSessionManager _sessionManager,UserSessionRelationManager _relationManager,LeaveMessageCacheManager _leaveMessageCacheManager){
        this.sessionManager = _sessionManager;
        executor = new MessageExecutorChain(new CommonMessageHandlerInitializer(_sessionManager,_relationManager,_leaveMessageCacheManager));
    }



    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Message message) throws Exception {

        executor.execute(ctx.channel(),message);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();
        String sessionid = channel.id().asShortText();
        IMSession session = new IMSession();
        session.setId(sessionid);
        session.setChannel(channel);
        sessionManager.create(session);

        logger.info("[server] " + sessionid + " 上线");
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();

        String sessionid = channel.id().asShortText();
        sessionManager.delete(sessionid);

        logger.info("[server] " + sessionid + " 离线");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //do nothing
        super.exceptionCaught(ctx, cause);
    }


}
